package leetcode.code117;

import leetcode.helper.tree.Node;

public class Solution extends Solution117 {

	@Override
	public Node connect(Node root) {
		if (root == null)
			return root;
		if (root.left != null) {
			if (root.right != null) {
				root.left.next = root.right;
			} else {
				Node temp = root.next;
				while (temp != null) {
					if (temp.left != null) {
						root.left.next = temp.left;
						break;
					} else if (temp.right != null) {
						root.left.next = temp.right;
						break;
					} else {
						temp = temp.next;
					}
				}
			}
		}
		if (root.right != null && root.next != null) {
			Node temp = root.next;
			while (temp != null) {
				if (temp.left != null) {
					root.right.next = temp.left;
					break;
				} else if (temp.right != null) {
					root.right.next = temp.right;
					break;
				} else {
					temp = temp.next;
				}
			}
		}
		this.connect(root.right);
		this.connect(root.left);
		return root;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
//		so.debug1();
//		so.debug2();
//		so.debug3();
		so.debug4();
	}

}
